package org.tls.ylt.user.service.Impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.tls.ylt.common.helper.EmailHelper;
import org.tls.ylt.common.result.Result;
import org.tls.ylt.user.service.EmailService;
import org.tls.ylt.vo.email.EmailVo;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class EmailServiceImpl implements EmailService {

    @Autowired
    EmailHelper emailHelper;
    @Autowired
    RedisTemplate<String,String> redisTemplate;

    @Override
    public boolean send(EmailVo emailVo) {
        System.out.println("接收到MQ消息");
        if(!StringUtils.isEmpty(emailVo.getEmail())) {
            Map<String, Object> param = emailVo.getParam();
            String content = "尊敬的"+param.get("name")+",您在"+param.get("reserveDate")
                    +"有一场医疗预约，订单取消的截止时间为"+param.get("quitTime");
            return this.send(emailVo.getEmail(),content);
        }
        return false;
    }

    /**
    发送验证码邮件
     */
    @Override
    public boolean send(String email) {
        System.out.println("准备发送邮件");
        //从redis获取验证码，如果获取获取到，返回ok
        // key 手机号  value 验证码
        String oldCode = redisTemplate.opsForValue().get(email);
        if (!StringUtils.isEmpty(oldCode))  return false;
        //如果从redis获取不到，
        //生成验证码
        String newCode = emailHelper.send(email);
        //生成验证码放到redis里面，设置有效时间
        if (!StringUtils.isEmpty(newCode)) {
            redisTemplate.opsForValue().set(email, newCode, 3, TimeUnit.MINUTES);
            System.out.println("验证码发送成功！");
            return true;
        }
        return false;
    }

    /**
     发送通知邮件
     */
    @Override
    public boolean send(String email,String content) {
        System.out.println("准备发送邮件");
        //生成验证码放到redis里面，设置有效时间
        if (emailHelper.send(email,content)) {
            System.out.println("通知邮件发送成功！");
            return true;
        }
        return false;
    }

}
